import * as vscode from 'vscode';
import * as path from 'path';
import { HighlightManager } from './HighlightManager';

export interface MessageHandlerOptions {
    highlightManager: HighlightManager;
}

export class MessageHandler {
    private highlightManager: HighlightManager;

    constructor(options: MessageHandlerOptions) {
        this.highlightManager = options.highlightManager;
    }

    public handleMessage(message: any): void {
        if (!message || typeof message !== 'object') {
            console.warn('Received invalid message:', message);
            return;
        }

        switch (message.cmd) {
            case 'open_file':
                this.handleOpenFile(message);
                break;
            case 'error':
                vscode.window.showErrorMessage(message.desc || '未知错误');
                break;
            case 'warn':
                vscode.window.showWarningMessage(message.desc || '未知警告');
                break;
            case 'info':
                vscode.window.showInformationMessage(message.desc || '信息提示');
                break;
            case 'script_result':
                vscode.window.showInformationMessage(message.desc || '脚本执行结果');
                break;
            default:
                console.log('Unknown message command:', message.cmd);
        }
    }

    private handleOpenFile(message: any): void {
        const workspaceFolders = vscode.workspace.workspaceFolders;
        if (!workspaceFolders) {
            vscode.window.showErrorMessage('请先打开一个工作区');
            return;
        }

        const rootPath = workspaceFolders[0].uri.fsPath;
        let fullPath = "";
        
        if (!rootPath.endsWith("/script")) {
            fullPath = path.join(rootPath, "script", message.path || '');
        } else {
            fullPath = path.join(rootPath, message.path || '');
        }

        this.highlightManager.highlightError({
            filePath: fullPath,
            line: message.line || 0,
            column: message.column || 1,
            description: message.desc || "错误信息xxxxxx"
        });
    }
}
